package main

import (
	"encoding/json"
	"log"
	"os"
	"os/user"
	"path/filepath"
)

// Config 结构体定义了配置文件的结构
type Config struct {
	Port         string                 `json:"port"`
	LogDir       string                 `json:"log_dir"`
	DataDir      string                 `json:"data_dir"`
	DefaultGroup string                 `json:"default_group"`
	BadgerOpts   map[string]interface{} `json:"badger_opts"`
	Split        byte                   `json:"split"`
}

// loadConfig 加载配置文件或使用默认配置
func loadConfig(path string) (*Config, error) {

	// 获取用户目录
	u, err := user.Current()

	if err != nil {
		log.Fatalf("Failed to get executable path: %v", err)
	}

	defaultLogDir := filepath.Join(u.HomeDir, "badger", "logs")
	defaultDataDir := filepath.Join(u.HomeDir, "badger", "data")

	var config = &Config{
		Port:         ":8099",
		LogDir:       defaultLogDir,
		DataDir:      defaultDataDir,
		DefaultGroup: "~",
		BadgerOpts:   make(map[string]interface{}),
		Split:        '~',
	}

	if path != "" {
		data, err := os.ReadFile(path)
		if err != nil {
			return nil, err
		}
		config = &Config{}
		err = json.Unmarshal(data, config)
		if err != nil {
			return nil, err
		}
	}

	// 确保目录存在
	if err := os.MkdirAll(config.LogDir, 0755); err != nil {
		log.Fatalf("Failed to create log directory: %v", err)
	}
	if err := os.MkdirAll(config.DataDir, 0755); err != nil {
		log.Fatalf("Failed to create data directory: %v", err)
	}

	return config, nil
}
